;(function(){

  /**
   * @param {boolean} isFolding  是否折叠  true 折叠  false 不折叠
   */
  var sidebar = function(isFolding){
    // 侧边栏根据用户屏幕高度定高滑动
    var setScrollHeight = function(){
      var topBarHeight = $('.cm-header').outerHeight(true);
      var bottomMargin = 0;
      var screenHeight = window.innerHeight;

      var setHeight = screenHeight - topBarHeight - bottomMargin;

      $('.cm-sidebar').css({'height':setHeight})
      $('.cm-content').css({'height':setHeight})
    }

    setScrollHeight()
    $(window).resize(setScrollHeight)

    // 侧边栏滚动时监听
    $('.cm-sidebar').scroll(function(){
      var scrollTop = $(this).scrollTop();
      if( scrollTop > 20 ) $('.init-tips-container').hide()
      if( scrollTop <= 20 ) $('.init-tips-container').show()
    })
    // 点击侧边栏时右侧内容回到顶部
    $('.cm-sidebar').on('click','.js-showRemove-nav',function(){
      $('html,body').animate({ scrollTop: 0 }, 500);
    })
    // 侧边栏折叠
    if(isFolding == false) return false
    $('.cm-sidebar').on('click','.cm-tab-item-title',function(){
      $(this).next('.cm-tab-item-container').stop(true).slideToggle()
      $(this).parent('.js-index-nav').siblings().find('.cm-tab-item-container').hide()

    })

  }

  /**
   * @param {string} selector 换肤对象选择器
   */
  var changeSkin = function(selector){
    function skin(val) {
        var result;

        switch (val) {
            case 'default':
                result = 'styles/app/' + val + '/default.min.css';
                break;
            case 'yellow':
                result = 'styles/app/' + val + '/yellow.min.css';
                break;
            case 'blue':
                result = 'styles/app/' + val + '/blue.min.css';
                break;
            case 'winered':
                result = 'styles/app/' + val + '/winered.min.css';
                break;
            default:
                result = '';
        }
        return result;
    }
    function favicon(val) {
        return 'favicon_' + val + '.ico';
    }

    if (!selector) return false;
    // 换肤
    var changeColor = document.querySelectorAll(selector);
    var lkCr = window.localStorage.getItem('lkHr');
    var lk = document.createElement('link');
    lk.rel = 'stylesheet';

    document.querySelector('head').appendChild(lk)
    lk.href = skin(lkCr);

    // 换网站图标
    if(lkCr){
        $('.favicon_index').attr('href',favicon(lkCr))
    }

    for (var i = 0; i < changeColor.length; i++) {
        changeColor[i].addEventListener('click', function() {
            var lkHf = this.getAttribute('data-skin');
            window.localStorage.setItem('lkHr', lkHf);
            lk.href = skin(lkHf);
            $('.favicon_index').attr('href',favicon(lkHf));
        }, false)
    }

  }

  window.sidebar = window.sidebar == undefined ? sidebar : window.sidebar
  window.changeSkin = window.changeSkin == undefined ? changeSkin : window.changeSkin
}())
